// pages/music-player/music-player.js
import {reqgetsongdetail, reqgetLyric} from "../../service/player"
import { throttle } from 'underscore'
import {parseLyric} from "../../utils/parseLyric"
import playerStore from "../../store/playerStore"
const app = getApp()
// 创建播放器
const audioContext = wx.createInnerAudioContext()
const modeNames = ["order", "repeat", "random"]
Page({
  data: {
    id: 0,
    currentSong: {},
    lyricInfos: [],
    statusHeight: 20,
    currentPage: 0,
    contentHeight: 0,
    pageTitles: ["歌曲", "歌词"],
    currentLyricText: "-----",
    currentTime: 0,
    durationTime: 0,
    sliderValue: 0,
    isSliderChanging: false,
    isplaying: true,
    lyricScrollTop: 0,
    playSongIndex: 0,
    playSongList: [],
    playModeIndex: 0, // 0:顺序播放 1:单曲循环 2:随机播放
    playModeName: "order"
  },

  onLoad(options) {
    const id = options.id
    this.setupPlaySong(id)
  },
  // ------歌曲播放------
  setupPlaySong(id){
    this.setData({id})
    // 获得歌曲详情&&歌词
    reqgetsongdetail(id).then(res => {
      this.setData({
        currentSong: res.songs[0],
        durationTime: res.songs[0].dt
      })
    })
    reqgetLyric(id).then(res => {
      const lrcString = res.lrc.lyric
      const lyricInfos = parseLyric(lrcString)
      this.setData({lyricInfos})
    })
    this.setData({ 
      statusHeight: app.globalData.statusHeight,
      contentHeight: app.globalData.contentHeight
     })
    // 3.获取store共享数据
    playerStore.onStates(["playSongList", "playSongIndex"], this.getPlaySongInfosHandler)
    // 播放当前的歌曲
    audioContext.stop() //停止上次播放
    audioContext.src = `https://music.163.com/song/media/outer/url?id=${id}.mp3`
    audioContext.autoplay = true // 设置自动播放，后面使用onCanplay
    // 监听播放的进度
    const throttleUpdateProgress = throttle(this.updateProgress, 500, { 
      leading: false,
      trailing: false 
    })
    audioContext.onTimeUpdate(() => {
      if(!this.data.isSliderChanging){
        throttleUpdateProgress()
      }
      // 匹配正确的歌词
      if (!this.data.lyricInfos.length) return
      let index = this.data.lyricInfos.length - 1
      for(let i = 0; i < this.data.lyricInfos.length; i++){
        const info = this.data.lyricInfos[i]
        if(info.time > audioContext.currentTime * 1000){
          index = i - 1
          break
        }
      }
      if (index === this.data.currentLyricIndex) return
      let currentLyricText = this.data.lyricInfos[index]?.text
      if(currentLyricText === undefined) currentLyricText = ""
      this.setData({ currentLyricText, currentLyricIndex: index, lyricScrollTop: 35 * index })
    })
    // 播放滑块拖动后滑块和时间不变化，需要设置一定等待时间
    audioContext.onWaiting(() => {
      audioContext.pause()
    })
    // 设置等待时间可以播放后播放
    audioContext.onCanplay(() => {
      audioContext.play()
    })
    audioContext.onEnded(() => {
      if(audioContext.loop) return
      this.changeNewSong()
    })
  },
  // 监听播放进度
  updateProgress(){
     // 记录当前时间
     this.setData({currentTime: audioContext.currentTime * 1000})
     // 修改进度条sliderValue
     const sliderValue = this.data.currentTime / this.data.durationTime * 100
     this.setData({sliderValue})
  },
  // 切换歌曲页和歌词页(滑动)
  changeCurrentPage(event){
    this.setData({currentPage: event.detail.current})
  },
  // 切换歌曲页和歌词页(点击title)
  onNavTabItemTap(event){
    const index = event.currentTarget.dataset.index
    this.setData({ currentPage: index })
  },
  // 播放滑块拖动后触发的事件
  onSliderChange(event){
    // 获取点击滑块位置对应的value
    const value = event.detail.value
    // 计算出要播放的位置时间
    const currentTime = value / 100 * this.data.durationTime
    // 设置播放器, 播放计算出的时间
    audioContext.seek(currentTime / 1000)
    this.setData({currentTime, sliderValue:value, isSliderChanging: false})
  },
  // 播放滑块拖动过程中触发的事件
  onSliderChanging(event){
    this.data.isSliderChanging = true
    const value = event.detail.value
    const currentTime = value / 100 * this.data.durationTime
    this.setData({ currentTime })
  },
  // 播放暂停切换
  onPlayOrPauseTap(){
    // 可以根据isplaying的值或者audioContext.paused来控制调用暂停和播放
    if(!audioContext.paused){
      audioContext.pause()  //暂停
      this.setData({isplaying: false})
    }else{
      audioContext.play()
      this.setData({isplaying: true})
    }
  },
  // 返回上一页
  toPrevious(){
    wx.navigateBack()
  },
  // onPrevBtnTap上一首
  onPrevBtnTap(){
    this.changeNewSong(false)
  },
  // onNextBtnTap下一首
  onNextBtnTap(){
     this.changeNewSong()
  },
  // 切换上下首歌曲函数
  changeNewSong(isNext = true){
    // 1.获取之前的数据
    const lenght = this.data.playSongList.length
    let index = this.data.playSongIndex
    // 2.根据之前的数据计算最新的索引
    switch(this.data.playModeIndex){
      case 0: // 顺序播放
      case 1:
        index = isNext ? index + 1 : index - 1
        if(index == lenght) index = 0
        if(index == -1) index = lenght - 1
        break
      // case 1: // 循环播放
      //   break
      case 2: // 随机播放
        index = Math.floor(Math.random() * lenght)
        break
    }
    // 3.根据索引获取当前歌曲的信息
    const newSong = this.data.playSongList[index]
    this.setupPlaySong(newSong.id)
    // 4.将数据回到初始状态
    this.setData({ currentSong: {}, sliderValue: 0, currentTime: 0, durationTime: 0, isplaying: true})
    // 5.保存最新的索引值
    playerStore.setState("playSongIndex", index)
  },
  // 切换播放模式：顺序、循环、随机
  onModeBtnTap(){
    // 计算新的模式
    let modeIndex = this.data.playModeIndex
    modeIndex = modeIndex + 1
    if(modeIndex === 3) modeIndex = 0
    if(modeIndex === 1){
      audioContext.loop = true
    } else {
      audioContext.loop = false
    }
    this.setData({playModeIndex: modeIndex, playModeName: modeNames[modeIndex]})
  },
  // ====================== store共享数据 ====================
  getPlaySongInfosHandler({ playSongList, playSongIndex }) {
    if (playSongList) {
      this.setData({ playSongList })
    }
    if(playSongIndex !== undefined){
      this.setData({ playSongIndex })
    }
  },

  onUnload() {
    playerStore.offStates(["playSongList", "playSongIndex"], this.getPlaySongInfosHandler)
  }
})